#!/usr/bin/python3
# -*- coding:utf-8 -*-

"""
    生成一个密码
    要求：必须包括大写字母，小写字母，数字和下划线,并且不能以数字开头
"""

import random
import string
import time


def pwd_generator(lenth=16):
    if lenth < 4 or lenth > 16:
        return '密码不合法'
    while True:
        password = ['_']

        char_list = [
            *string.ascii_uppercase,
            *string.ascii_lowercase,
            *string.digits
        ]

        for _ in range(lenth - 1):
            random_pwd = random.choice(char_list)
            password.append(random_pwd)

        random.shuffle(password)
        password = ''.join(password)

        ls = [False for _ in range(4)]
        for word in password:
            if 97 <= ord(word) <= 122:  # 必须有小写字母
                ls[0] = True
            if 65 <= ord(word) <= 90:  # 必须有大写字母
                ls[1] = True
            if 48 <= ord(word) <= 57:  # 必须有数字
                ls[2] = True
            if not password[0].isdigit():  # 不能以数字开头
                ls[3] = True

        if all(ls):  # 只有4个条件同时满足才可以。
            return password
        print('密码不合法', password)
        time.sleep(1)


res = pwd_generator()
print(res)

